package com.example.demo.handler;

import com.example.demo.common.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseData<String> handleException(Exception e){
                //返回异常时要返回的响应
                return ResponseData.fail("发生异常"+e.getMessage());
        }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseData<String> handleValidationException(MethodArgumentNotValidException ex){
                StringBuilder errors=new StringBuilder();
                ex.getBindingResult().getFieldErrors().forEach(error->errors.append(error.getDefaultMessage()).append(";"));
            return ResponseData.fail(errors.toString());
    }
}
//    import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.ControllerAdvice;
//import org.springframework.web.bind.annotation.ExceptionHandler;
//import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
//
//    @ControllerAdvice
//    public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
//
//        // 处理所有自定义异常
//        @ExceptionHandler(CustomException.class)
//        public ResponseEntity<String> handleCustomException(CustomException e) {
//            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
//        }
//
//        // 处理所有运行时异常
//        @ExceptionHandler(RuntimeException.class)
//        public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
//            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//        }
//
//        // 处理所有异常
//        @ExceptionHandler(Exception.class)
//        public ResponseEntity<String> handleAllExceptions(Exception e) {
//            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//        }
//    }


